package com.sykj.why.mongo.service.impl;

import com.sykj.why.exception.WhyException;
import com.sykj.why.mongo.dao.UserTDao;
import com.sykj.why.mongo.document.entity.SystemMenuT;
import com.sykj.why.mongo.document.entity.UserT;
import com.sykj.why.mongo.dto.PageDTO;
import com.sykj.why.mongo.dto.entity.UpdatePwdDTO;
import com.sykj.why.mongo.enums.exception.ResultEnum;
import com.sykj.why.mongo.service.UserTService;
import com.sykj.why.mongo.vo.entity.UserTVo;
import com.sykj.why.util.BaseTools;
import com.sykj.why.util.DateTool;
import com.sykj.why.util.Page;
import com.sykj.why.util.SHA1;
import org.apache.commons.lang3.StringUtils;
import org.omg.CORBA.UserException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Eleven
 * @date 2016/6/5
 * @desc 后台用户业务实现层
 */

@Service("UserTService")
public class UserTServiceImpl extends BasicServiceImpl<UserT> implements UserTService {

    @Autowired
    private UserTDao userTDao;

    /**
     * 添加用户
     * @param userT
     */
    @Override
    public void saveUser(UserT userT) {
        //验证用户名称是否重复
        verifyName(userT);
        //排序
        long count = userTDao.count(UserT.class, false);
        userT.setSort((int) count);
        //设置初始密码
        userT.setPassWord(SHA1.getDigestOfString("111111"));
        if (userT.getTrueName() == null){
            userT.setTrueName(userT.getUserName());
        }
        if (userT.getRole() == null){
            userT.setRole("管理员");
        }
        //设置时间
        userT.setCreateTime(DateTool.getSystemTime());
        userT.setUpdateTime(DateTool.getSystemTime());
        //保存
        userTDao.save(userT);
    }

    /**
     * 删除用户
     * @param id
     */
    @Override
    public void removeUser(String id) {
        //通过Id查询用户
        UserT userT = findById(id);
        //逻辑删除用户
        userTDao.remove(userT);
    }

    /**
     * 修改用户
     * @param userT
     */
    @Override
    public void updateUser(UserT userT) {
        //通过id查询用户
        UserT user = findById(userT.getId());
        //重新赋值
        //验证用户名称是否重复
        verifyName(userT);
        user.setUserName(userT.getUserName());
        user.setTrueName(userT.getTrueName());
        user.setRole(userT.getRole());
        user.setUpdateTime(DateTool.getSystemTime());
        //保存或修改
        userTDao.saveOrupdate(user);
    }

    /**
     * 启用/禁用用户
     * @param id
     * @param flag
     */
    @Override
    public void disableOrEnable(String id, boolean flag) {
        //通过id查询用户
        UserT userT = findById(id);
        //修改状态
        userTDao.disableOrEnable(userT,flag);
    }

    /**
     * 验证用户名称是否重复
     * @param userT
     */
    @Override
    public void verifyName(UserT userT) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").ne(userT.getId()).
                and("userName").is(userT.getUserName()).and("removed").is(false));
        UserT user = userTDao.findOne(query,UserT.class);
        if (user != null) {
            throw new WhyException(ResultEnum.REPEAT);
        }
    }

    /**
     * 通过id查询用户
     * @param id
     * @return
     */
    @Override
    public UserT findById(String id) {
        //通过id查询未删除的用户
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id).and("removed").is(false));
        UserT userT = userTDao.findOne(query,UserT.class);
        if (userT!=null){
            return userT;
        }else {
            throw new WhyException(ResultEnum.OBJISNULL);
        }
    }

    /**
     * 查询所有用户
     * @return
     */
    @Override
    public List<UserT> findAll() {
        //查询未删除和未禁用的所有用户
        Query query = new Query();
        query.addCriteria(Criteria.where("removed").is(false).and("enable").is(true));
        List<UserT> list = userTDao.findAll(query,UserT.class);
        return list;
    }

    /**
     * 分页查询用户
     * @param pageDTO
     * @return
     */
    @Override
    public Page findByPage(PageDTO pageDTO) {
        //查询未删除的用户，并分页传给视图
        Query query = new Query();
        query.addCriteria(Criteria.where("removed").is(false));
        if (StringUtils.isNoneEmpty(pageDTO.getParamName())){
            query.addCriteria(new Criteria().orOperator(
                    Criteria.where("userName").regex(pageDTO.getParamName()),
                    Criteria.where("trueName").regex(pageDTO.getParamName())
            ));
        }
        long count = userTDao.count(query, UserT.class);
        List<UserTVo> list = new ArrayList<>();
        for (UserT userT : userTDao.findByPage(query, pageDTO, UserT.class)) {
            UserTVo vo = new UserTVo();
            BeanUtils.copyProperties(userT, vo);
            vo.setCreateTime(BaseTools.longToString(userT.getCreateTime()));
            vo.setUpdateTime(BaseTools.longToString(userT.getUpdateTime()));
            list.add(vo);
        }
        return new Page(pageDTO, count, list);
    }

    /**
     * 通过用户信息查找用户
     * @param userT
     * @return
     */
    @Override
    public UserT getUser(UserT userT) {
        Query query = new Query();
        query.addCriteria(Criteria.where("removed").is(false).and("userName").is(userT.getUserName()));
        UserT user1 = userTDao.findOne(query,UserT.class);
        if (user1 == null){
            throw new WhyException(ResultEnum.USER_NOT_EXIST);
        }else {
            query.addCriteria(Criteria.where("enable").is(true));
            UserT user2 = userTDao.findOne(query,UserT.class);
            if (user2 == null){
                throw new WhyException(ResultEnum.USER_ENABLE);
            }else {
                query.addCriteria(Criteria.where("passWord").is(SHA1.getDigestOfString(userT.getPassWord())));
                UserT user3 = userTDao.findOne(query,UserT.class);
                if (user3 == null){
                    throw new WhyException(ResultEnum.USER_NAME_OR_PASSWORD_WRONG);
                }
                return user3;
            }
        }
    }

    /**
     * 修改密码
     * @param id
     * @param passWord
     */
    @Override
    public void updatePassWord(String id,String passWord) {
        UserT userT = findById(id);
        if (passWord!=null){
            //修改密码
            userT.setPassWord(SHA1.getDigestOfString(passWord));
        }else {
            //重置密码
            userT.setPassWord(SHA1.getDigestOfString("111111"));
        }
        userT.setUpdateTime(DateTool.getSystemTime());
        userTDao.saveOrupdate(userT);
    }

}
